package com.zhang.zxx.boot.common.exception;


import com.zhang.zxx.boot.common.enums.MsgEunm;
import lombok.EqualsAndHashCode;
import lombok.Getter;

import java.util.Optional;

/**
 * BusinessException:业务异常
 *
 * @author zhangxiaoxiang
 * @date 2021年11月27日
 */
@EqualsAndHashCode(callSuper = true)
public class BusinessException extends RuntimeException {

    private static final String FORMAT_STR = "00000";
    /**
     * eMsg拆分
     */
    @Getter
    private final String eMsgCode;
    /**
     * 调试数据
     */
    @Getter
    private Object debugData;
    /**
     * 是否打印详情
     */
    @Getter
    private boolean printDetail = true;

    public BusinessException(MsgEunm msgEunm, String customMsg) {
        super(customMsg);
        this.eMsgCode = msgEunm.getCode();
    }

    public BusinessException(Integer code, String customMsg) {
        super(customMsg);
        code = Optional.ofNullable(code).orElse(Integer.parseInt(MsgEunm.FAILED.getCode()));

        String codeStr = String.valueOf(code);
        if (code > 99999) {
            this.eMsgCode = codeStr;
        } else {
            this.eMsgCode = FORMAT_STR.substring(0, FORMAT_STR.length() - codeStr.length()) + codeStr;
        }
    }

    public BusinessException(MsgEunm msgEunm) {
        super(msgEunm.getMessage());
        this.eMsgCode = msgEunm.getCode();
    }

    public BusinessException setDebugData(Object debugData) {
        this.debugData = debugData;
        return this;
    }

    @Override
    public synchronized BusinessException initCause(Throwable cause) {
        return (BusinessException) super.initCause(cause);
    }

    public BusinessException setPrintDetail(boolean printDetail) {
        this.printDetail = printDetail;
        return this;
    }
}
